import { Component, OnInit } from '@angular/core';
import { Utils, Lang, Status } from '../../../../common/helper/util-helper';
import { NzModalService, NzMessageService } from 'ng-zorro-antd';
import { RoleService } from '../../../../services/organization/Role/role.service';
// 项目成员服务
import { MemberManageService } from '../../../../services/project/project-member/member-manage.service';
// 组织机构人员服务
import { MemberService } from '../../../../services/organization/member/member.service';
import { DepartmentService } from '../../../../services/organization/department/department.service';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { memberModel } from './member-manage.model';
import { Router } from '@angular/router';

@Component({
  selector: 'app-member-manage',
  templateUrl: './member-manage.component.html',
  styleUrls: ['./member-manage.component.scss']
})
export class MemberManageComponent implements OnInit {

  public projectName: string = JSON.parse(window.localStorage.getItem('project')).name;
  public projectId: string = JSON.parse(window.localStorage.getItem('project')).id;
  public createUserId = JSON.parse(window.localStorage.getItem('project')).creatorUserId;
  public userId = JSON.parse(window.localStorage.getItem('APDInfo')).userId;
  public status = {

    // 列表数据集合
    dataList: [],
    // 权限集合
    authority: [],
    // 禁止修改权限点
    cantModify: false,
    // 所有权限集合
    permissions: [],

    // 获取的人员数据集合
    memberOptions: [],
    // 下拉框选择的人员数据
    memberValue: null,
    // 是否启用下拉框
    canChange: false,
    // 批量删除按钮状态
    delBtnStatus: false,
    // 全选状态
    allChecked: false,
    // 半选状态
    indeterminate: false,
    // 选择框当前选中的数据集合
    checkedDatas: [],
    // 关键词搜索
    filter: '',
    // 当前选中节点
    activedNode: null,
    // 待编辑节点
    editNode: null,
    // 修改结构模态框状态
    ischangeSort: false,
    // 新增部门模态框状态
    ismodify: false,
    // 编辑部门模态框状态
    isedit: false,
    // 删除部门模态框
    isDelete: false,
    // 结构修改成功状态
    isOkLoading: false,
    // 状态按钮
    isLoding: false,
    // 防止用户重复点击
    statusDisabled: false,
    // 模态框按钮提交状态
    isConfirmLoading: false,
    // 新增部门模态框状态
    isadd: false,
    // 项目成员表单数据绑定集合
    member: {
      job: null,
      id: null
    },
    // 分页相关数据集合对象
    pager: {
      // 当前页
      pageIndex: 1,
      // 总记录数
      totalCount: 1,
      // 每页显示记录数
      pageSize: 10,
      // 总页数
      totalPages: 1
    },
    // 选中的权限
    ChoosedRoleAuthority: null,
    // 需要显示的权限菜单列表
    authorityObjs: {
      'APJ.PI': true,
    },
    // 当前页面所需要的权限
    PIpagePermissions: [
      // 项目成员管理
      'APJ.PI.ProjectUser',
    ],
    // 当前页面权限
    PIpageAuthorty: {
      PIProjectUser: null,
    },

  };

  routeToSurvey() {
    const projectId = JSON.parse(window.localStorage.getItem('project')).id;
    this.router.navigate([`/inner/project/${projectId}/survey`], {queryParams: { info: 'project' }});
  }



  // 初始化数据
  init() {
    // 匹配权限
    console.log( this.userId ,this.createUserId);
    if (JSON.parse(window.localStorage.getItem('APDInfo'))['roleCode'] !== 'Admin' && this.userId !== this.createUserId) {
      this.status.PIpageAuthorty = Utils.PIgrantedPermissions(
        this.status.PIpagePermissions,
        this.status.PIpageAuthorty,
        true
      );
    } else {
      // admin 角色拥有该页面权限
      // tslint:disable-next-line: forin
      for (const key in this.status.PIpageAuthorty) {
        console.log(key);
        this.status.PIpageAuthorty[key] = true;
      }
    }
    console.log(this.status.PIpageAuthorty);
    // 刷新数据重置全选、半选状态, 批量删除按钮状态,清空选中项
    this.status.allChecked = false;
    this.status.indeterminate = false;
    this.status.checkedDatas = [];
    if (this.status.checkedDatas.length === 0) {
      this.status.delBtnStatus = true;
    }
    const pramas = {
      // 每页记录数
      maxResultCount: this.status.pager.pageSize,
      // 当前页数
      SkipCount: this.status.pager.pageIndex - 1,
      // 关键词搜索
      filter: this.status.filter,
      projectId: this.projectId
    };
    // 加载项目成员列表
    this.memberManageService.QueryProjectUsersPagedList(pramas).then((res) => {
      if (res.success) {
        this.status.dataList = res.result.items || [];
        this.status.pager.totalCount = res.result.totalCount;
        this.status.pager.totalPages = res.result.totalCount;
      } else {
        this.message.warning(res.error.message);
      }

      // 加载人员选项
      this.memberService.GetUsers({ maxResultCount: 2000 }).then((res) => {
        if (res.success) {
          const Temp = res.result.items;
          const tempOrg = [];
          Temp.forEach(element => {
            tempOrg.push({ label: element.name, value: element.primaryId });
          });
          this.status.memberOptions = tempOrg;
        } else {
          this.message.warning(res.error.message);
        }
      });

    });
    // 获取所有权限列表
    this.roleService.GetRoleForEdit().then((res) => {
      console.log(res);
      if (res.success) {
        // 保存权限集合
        const permissions = res.result.permissions;
        this.status.permissions = res.result.permissions;
        // 保存当前角色拥有的权限
        const grantedPermissionNames = res.result.grantedPermissionNames;
        // 处理权限数据
        this.disposePermissionsData(permissions, grantedPermissionNames);
      } else {
        this.message.warning(res.error.message);
      }
    });
  }



  /**************************************************权限数据处理***************************************************** */

  /**
     * 处理权限数据 生成权限点
     * @param permissions 权限数据
     */
  private disposePermissionsData(permissions, grantedPermissionNames) {
    // console.log(permissions);

    // 获取首级
    const tempPermission = {};
    const authorityObjs = this.status.authorityObjs;
    // 总权限数据
    Utils.resetData(permissions, (permission) => {
      const permissionKey = permission.name;
      // 匹配权限关键字
      // 如果能在authorityObjs 找到该权限
      if (authorityObjs[permissionKey]) {
        tempPermission[permissionKey] = tempPermission[permissionKey] || {
          text: null,
          key: null,
          group: []
        };
        tempPermission[permissionKey].text = permission.displayName;
        tempPermission[permissionKey].key = permissionKey;
      } else {
        for (const key in authorityObjs) {
          if (permissionKey.indexOf(key) > -1) {
            // 权限组集合
            let groupItem = tempPermission[key];
            if (!groupItem) {
              groupItem = { text: null, key: null, group: [] };
              tempPermission[key] = groupItem;
            }
            groupItem.group = groupItem.group || [];
            let checkStatus = false;
            Utils.resetData(grantedPermissionNames, (nameItem) => {
              if (permissionKey === nameItem) {
                checkStatus = true;
                return 'break';
              }
            });
            groupItem.group.push({
              value: permissionKey,
              label: permission.displayName,
              key: permissionKey,
              checked: checkStatus
            });
          }
        }
      }
    });
    // 重新排序Permissions
    // 排序后的新数组
    // console.log(tempPermission)
    const reOrderPermissions = [];
    for (const key in tempPermission) {
      // console.log(tempPermission[key])
      if (key === 'APJ.PI') {
        reOrderPermissions[0] = tempPermission[key];
      }

    }
    // 保存排序后的权限数组
    this.status.authority = reOrderPermissions;
    // console.log(this.status.authority)

  }

  /**
     * 添加或编辑时，获取当前选中的角色权限
     */
  private getChoosedRoleAuthority() {
    const resultAuthority = [];


    // 获取当前选中的权限点
    const authority = this.status.authority;
    let i = 0,
      len = authority.length,
      authorityItem;
    for (; i < len; i++) {
      authorityItem = authority[i];
      const group = authorityItem.group;
      let j = 0,
        lenJ = group.length,
        groupItem;
      for (; j < lenJ; j++) {
        groupItem = group[j];
        if (groupItem.checked) {
          resultAuthority.push(groupItem.key);
          // 还原状态
          // groupItem.checked = false;
        }
      }
    }
    // console.log(resultAuthority);
    return resultAuthority;
  }


  /**
   * 清空权限
   */
  private clearRoleAuthority() {
    const authority = this.status.authority;
    Utils.resetData(authority, (authorityItem) => {
      const group = authorityItem.group;
      Utils.resetData(group, (groupItem) => {
        groupItem.checked = false;
      });
    });
  }
  /**************************************************权限数据处理结束*************************************************** */


  // 选中相关************************************************************************************************************
  /**
     * 全部选中
     * @param status <any> 全选框的选中状态
     */
  public checkAll(status: any, callBack?: Function) {
    this.status.dataList.forEach((data: any) => {
      let eachStatus;
      if (callBack) {
        eachStatus = callBack(data);
      }
      if (eachStatus !== false) {
        data['checked'] = status;
      }
    });
    this.refreshCheckboxStatus();
  }

  /**
   * 刷新(所有复选框)状态
   */
  private refreshCheckboxStatus() {
    const dataList = this.status.dataList;
    const allChecked = dataList.filter((value: any) => !value['disabled']).every((value: any) => value['checked'] === true);
    const allUnChecked = dataList.filter((value: any) => !value['disabled']).every((value: any) => !value['checked']);
    this.status.allChecked = allChecked;
    this.status.indeterminate = (!allChecked) && (!allUnChecked);
    // 获取当前选中的数据
    const checkedDatas = [];
    dataList.forEach((data) => {
      if (data['checked']) {
        checkedDatas.push(data);
      }
    });
    this.status.checkedDatas = checkedDatas;
    // 改变批量操作按钮状态
    this.status.delBtnStatus = !dataList.some((value: any) => value['checked']);
  }
  /**
   * 获取当前选中项
   */
  public getCheckedData() {
    return this.status.checkedDatas;
  }
  // 选中相关结束********************************************************************************************************



  // 选择框改变事件
  selChange(value: { label: string; value: any; }): void {
    console.log(value);
  }
  // 绑定 输入框
  compareFn = (o1: any, o2: any) => (o1 && o2 ? o1.value === o2.value : o1 === o2);




  /***********************************
  *  // 获取选中部门的所有父级ID        *
  * @param currentid 当前选择部门的ID   *
  * @param arr 后台获取的所有部门数据   *
  * @param res 返回的 ID 数组         *
  ***********************************/
  public deepTraversal(currentid, arr, res) {
    if (arr != null) {
      arr.forEach(ele => {
        if (ele.id === currentid) {
          if (ele.parentId) {
            res.push(ele.parentId);
            this.deepTraversal(ele.parentId, arr, res);
          } else {
            return;
          }
        }
      });
    }
    return res;
  }


  // 新增成员
  addRole() {
    this.status.isadd = true;
    // console.log(this.status.orgValue)
    this.status.cantModify = false;
  }
  addSave() {
    if (!this.status.memberValue) {
      this.message.warning('人员不能为空');
    } else if (!this.status.member.job) {
      this.message.warning('岗位不能为空');
    } else {
      // 获取基础权限及选择的权限
      this.status.ChoosedRoleAuthority = this.getChoosedRoleAuthority();
      const params = {
        projectId: this.projectId,
        userId: this.status.memberValue.value,
        position: this.status.member.job,
        permissionArray: this.status.ChoosedRoleAuthority
      };
      // console.log(params)
      this.status.isOkLoading = true;
      this.memberManageService.AddUserOrModifyToProject(params).then((res) => {
        // console.log(res);
        if (res.success) {
          this.status.isadd = false;
          this.message.success('添加成功');
          this.init();
        } else {
          this.status.isadd = false;
          this.message.warning(res.error.message);
        }
        // 关闭输入框并清空输入框值
        this.cancelAddOredit();

      });
    }
  }

  // 编辑成员
  protected editRole(node) {
    console.log(node);
    // 如果当前编辑的成员ID = 项目创建员ID
    if (node.userId === this.createUserId) {
      this.status.cantModify = true;
    } else if (node.roleName === 'Admin') {
      this.status.cantModify = true;
    } else {
      this.status.cantModify = false;
    }
    this.status.isedit = true;
    this.status.editNode = node;
    this.status.memberValue = { label: node.name, value: node.userId };
    this.status.member.job = node.position;
    this.status.member.id = node.id;
    // 禁用人员选择
    this.status.canChange = true;

    // 获取当前编辑角色的权限点
    // 获取权限列表
    const params = {
      projectId: this.projectId,
      userId: node.userId
    };
    this.memberManageService.QueryPermissionByProjectUser(params).then((res) => {
      // console.log(res);
      if (res.success) {
        // 保存权限集合
        const permissions = this.status.permissions;
        // 保存当前角色拥有的权限
        // tslint:disable-next-line: no-eval
        const grantedPermissionNames = eval(res.result);
        // console.log(grantedPermissionNames)
        // 处理权限数据
        this.disposePermissionsData(permissions, grantedPermissionNames);
      } else {
        this.message.warning(res.error.message);
      }
    });

  }

  // 确定修改成员
  editSave() {
    // 获取基础权限及选择的权限
    this.status.ChoosedRoleAuthority = this.getChoosedRoleAuthority();
    const params = {
      projectId: this.projectId,
      userId: this.status.memberValue.value,
      position: this.status.member.job,
      id: this.status.member.id,
      permissionArray: this.status.ChoosedRoleAuthority
    };
    this.status.isOkLoading = true;
    // console.log(params);
    this.memberManageService.AddUserOrModifyToProject(params).then((res) => {
      // console.log(res)
      if (res.success) {
        this.message.success('修改成功');
        this.init();
      } else {
        this.message.warning(res.error.message);
      }
      // 关闭输入框并清空输入框值
      this.cancelAddOredit();

    });

  }
  // 取消编辑或添加
  cancelAddOredit() {
    this.status.canChange = false;
    this.status.editNode = null;
    this.status.isedit = false;
    this.status.isadd = false;
    this.status.isOkLoading = false;
    this.status.memberValue = null;
    // tslint:disable-next-line: forin
    for (const i in this.status.member) {
      this.status.member[i] = null;
    }
    console.log('数据已清除');
  }


  // 删除人员
  protected delRole(node) {
    // this.status.isDelete = true;
    this.status.editNode = node;
    // console.log(node)
    this.mzModal.error({
      nzTitle: '删除组织',
      nzContent: '<p>删除后不能恢复，请谨慎操作。</p>',
      nzOnOk: () => this.delNode(),
      nzOkText: '确定',
      nzOkType: 'danger',
      nzCancelText: '取消',
      nzOnCancel: () => { }
    });
  }
  // 确定删除人员
  delNode() {
    const params = {
      ProjectId: this.projectId,
      UserId: this.status.editNode.userId
    };
    // console.log(params)
    this.memberManageService.RemoveUserOnProject(params).then((res) => {
      if (res.success) {
        this.message.success('删除成功');
        this.init();
      } else {
        this.message.error(Utils.errorMessageProcessor(res, Lang.deleteFail));
      }
      this.status.isDelete = false;
      this.status.editNode = null;
      this.status.activedNode = null;
      // this.status.title = null;
      // this.status.description = null;
    });
  }

  // 取消删除
  Canceldel() {
    this.status.isDelete = false;
    this.status.editNode = null;
    this.status.activedNode = null;

  }


  // 批量删除人员？
  public delmembers() {
    this.mzModal.error({
      nzTitle: '批量删除',
      nzContent: '<p>确认要批量删除吗？删除后无法恢复</p>',
      nzOnOk: () => this.delRoles(),
      nzOkText: '确定',
      nzOkType: 'danger',
      nzCancelText: '取消',
      nzOnCancel: () => { }
    });
  }

  // 确定批量删除人员
  delRoles() {
    const params = {
      projectId: this.projectId,
      userIdList: []
    };
    this.getCheckedData().forEach((item) => {
      params.userIdList.push(item.userId);
    });
    console.log(params);
    if (params) {
      this.memberManageService.BatchRemoveUserOnProject(params).then((res) => {
        if (res.success) {
          this.message.success('删除成功');
        } else {
          this.message.warning(res.error.message);
        }
        // 重新加载
        this.init();
      });
    }
  }






  /*分页相关******************************************************************************** */
  /**
  * 刷新列表
  */
  public refreshDataList() {
    const refresh = this['init'].bind(this);
    if (refresh) {
      refresh();
    }
  }

  /**
   * 列表分页
   * @param index <number> 非必填，列表跳转至第几页，默认为当前页(即刷新当前页数据)
   */
  public pageIndexChange(index?: any) {
    // console.log(index)
    const pager = this.status.pager;
    pager.pageIndex = index || pager.pageIndex;
    this.refreshDataList();
  }

  /**
   * 改变每页记录条数
   * @param size <number> 非必填
   */
  public pageSizeChange(size?: number) {
    const pager = this.status.pager;
    pager.pageSize = size || pager.pageSize;
    this.pageIndexChange();
  }

  /**********************************************************************************分页相关结束 */

  /**
   * 关键字搜索
   */
  public searchEvent() {
    // 搜索时重置分页
    this.status.pager.pageIndex = 1;
    this.init();
  }

  /**
   * 搜索框回车事件
   * @param e <Event>
   */
  public keyupEvent(e: Event) {
    Utils.enter(e, this.searchEvent.bind(this));
  }




  // tslint:disable-next-line: max-line-length
  constructor(public memberManageService: MemberManageService, public memberService: MemberService, public mzModal: NzModalService, public roleService: RoleService, public message: NzMessageService, private router: Router, ) { }

  ngOnInit() {
    // 初始化批量删除按钮状态
    this.status.delBtnStatus = !this.status.dataList.some((value: any) => value['checked']);
    this.init();

  }

}
